package com.taikang.base.util;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**
 * 图片操作类
 * @author taikang
 *
 */
public class ImageUtil {
	
	/**
     * 裁剪图片
     * @param src
     * @param dest
     * @param x
     * @param y
     * @param w
     * @param h
     * @throws IOException
     */
    @SuppressWarnings("rawtypes")
	public static void cutImage(String src,String dest,int x,int y,int w,int h,String fileExt) throws IOException{   
        Iterator iterator = ImageIO.getImageReadersByFormatName(fileExt);   
        ImageReader reader = (ImageReader)iterator.next();   
        InputStream in=new FileInputStream(src);  
        ImageInputStream iis = ImageIO.createImageInputStream(in);   
        reader.setInput(iis, true);   
        ImageReadParam param = reader.getDefaultReadParam();   
        Rectangle rect = new Rectangle(x, y, w,h);    
        param.setSourceRegion(rect);   
        BufferedImage bi = reader.read(0,param);     
        ImageIO.write(bi, fileExt, new File(dest));             
    }
    
    /** 
     * 图片缩放 
     */  
    @SuppressWarnings("static-access")
	public static void zoomImage(String src,String dest,int w,int h) throws Exception {  
        double wr=0,hr=0;  
        File srcFile = new File(src);  
        File destFile = new File(dest);  
        BufferedImage bufImg = ImageIO.read(srcFile);  
        Image Itemp = bufImg.getScaledInstance(w, h, bufImg.SCALE_SMOOTH);  
        wr=w*1.0/bufImg.getWidth();  
        hr=h*1.0 / bufImg.getHeight();  
        AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);  
        Itemp = ato.filter(bufImg, null);  
        try {  
            ImageIO.write((BufferedImage) Itemp,dest.substring(dest.lastIndexOf(".")+1), destFile);  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
          
    }
    
    /**
     * 得到图片的宽高
     * @param src
     * @return
     * @throws IOException
     */
    public static int[] getImageWAndH(String src) throws IOException{
    	File srcFile = new File(src);  
    	BufferedImage bufImg = ImageIO.read(srcFile);
    	return new int[]{bufImg.getWidth(),bufImg.getHeight()};
    }
}
